//获取应用实例
let app = getApp();
let FormCheckRule = {
	courierNullMessage:"请输入邮件号",
	cardErrorMessage:"请扫描正确的邮件号",	
};

Page({
	data: {
		express: {}, //邮寄公司类型
		isFocus: false, //输入框获得焦点
		courierCodeIconType: '', //邮件号状态
		expressHistoryList: [],//历史数据
		courierCodeValue: '',//邮政号
    	isCanScroll: true, //屏幕是否能够滑动
		isShowFootNav: true,  //底部导航菜单
		num: 0  //订单数
	},
	//分享功能
	onShareAppMessage() {
		return {
			title: '查快递',
			desc: '查快递',
			path: '/pages/checkExpress/checkExpress'
		}
	},

	onLoad(options) {
	},

	onUnload() {
		app.setStorageSync('tagSign',1)
	},
	
	onShow(options) {
		let that = this;
		let expressHistory = app.getStorageSync(app.globalData.expressHistory),  //历史数据
			expressService = app.getStorageSync(app.globalData.expressService)? //默认邮寄公司类型 *ems
							 app.getStorageSync(app.globalData.expressService):{"com":"EMS","no":"ems"}, 
			page = app.getStorageSync(app.globalData.checkProgress);	//缓存												
		this.setData({
			expressHistoryList: expressHistory,
			express: expressService
		})
		app.getOrderNum((num,openId) => {
			that.setData(Object.assign({},page,{num: num}));
		})
	},

	//选择历史数据
	getExpressCompany(e) { 
		this.setData({
			express: e.target.dataset,
			courierCodeValue: e.target.dataset.comname
		})
	},

	//跳转查询首页
	toExpressList() {
		app.setStorageSync(app.globalData.checkProgress, this.data);
		app.navigateTo({url:'../searchList/searchList'})
	},

	//清除输入框内容
	closeInputText() {
		this.setData({
			courierCodeValue: '',
			courierCodeIconType: ''
		});
	},

	//条形码
    bindViewTap() {
        let that = this;
        let path= /^[0-9a-zA-Z]*$/g;
        wx.scanCode({
            success:(res) => {
                if (path.test(res.result)) {
					setTimeout(() => { //扫描二维码，会触发onShow
						that.setData({
							courierCodeValue: res.result,
						});
					},500)
                } else {
                    app.errorToast(FormCheckRule.cardErrorMessage);
                }
            }
        })
    },

	//输入框公用方法
	infoInput(e) {
		let value = e.detail.value,
			courierCodeValue = value.replace(/(^\s*)|(\s*$)/g,"").replace(/[^\w\.\/]/ig,'').toUpperCase() ; //只能输入数字和字母
		this.setData({courierCodeValue: courierCodeValue});  //限制只能输入字母和数字
		if (courierCodeValue.length>0) {
			this.setData({courierCodeIconType: "close"});
		} else {
			this.setData({
				courierCodeIconType: "",
				creditCode: courierCodeValue
			});
		}
	},

	infoBlur(e) {
		setTimeout(() => {		
			if (this.data.courierCodeIconType == '') {
				this.setData({
					courierCodeIconType: "",
					isFocus: true
				});			
			} else {
				this.setData({
					courierCodeIconType: "success"
				});	
			}
		},100)	
	},

	infoFocus(e) {
		let value = e.detail.value;
		if (value.length>0) {
			this.setData({courierCodeIconType: "close"});			
		}
	},

	//底部切换页面方法
	toUrl(e) {
		let url = e.currentTarget.dataset.url;
		if(url!='/pages/checkExpress/checkExpress'){
			if(url == ''){
				//develop（开发版），trial（体验版），release（正式版）
				let res = {
					appid: app.globalData.appid,
					path: '',
					envVersion: app.globalData.envVersion
				}
				app.crossToUrl(res)
			}else {
				app.setStorageSync(app.globalData.checkProgress, Object.assign({},this.data,{ popErrorMsg: '' },
				{errorFocusName:''}, {isCanScroll: true}));				
				app.redirectTo({url: url})
			}
		}
	},
	
	setHistory(value) {
		let queryHistory = app.getStorageSync(app.globalData.expressHistory) == null||!app.getStorageSync(app.globalData.expressHistory)?
							new Array():app.getStorageSync(app.globalData.expressHistory);
		if (!this.isExistsInArray(queryHistory, value)) { //先判断是否已存在缓存中，存在就删除，否则重新入队
            if (queryHistory.length == 10) {
                queryHistory.pop();//出队
			}
        } else {
			queryHistory = this.removeByValue(queryHistory,value);  //有相同的数据，删除存在的
		}
		
        queryHistory.unshift(value);//入队
		app.setStorageSync(app.globalData.expressHistory,queryHistory)
		this.setData({
			expressHistoryList: queryHistory
		})
	},

	//删除数组中某个值
    removeByValue(arr, val) {
		for(var i=0; i<arr.length; i++) {
			if (arr[i].comName == val.comName&&arr[i].comNo == val.comNo) {
				arr.splice(i, 1);
				return arr;
			}
		}
		return arr;
        
    },

	  //判断是否存在数组中
	isExistsInArray(array,value) {
		for(var i=0; i<array.length; i++) {
			if(array[i].comName == value.comName&&array[i].emsNo == value.emsNo) {
				return true;
			}
		}
		return false;
	},
	
	//清除邮政号历史记录
	cleanCache() {
		app.removeStorage(app.globalData.expressHistory)
		this.setData({
			expressHistoryList: []
		})
	},

	//确认提交按钮
	formSubmit(e) {
		let { courierCodeValue, express } = this.data;
		let history = {
			comNo: express.com,
			comName: courierCodeValue,
			emsNo: express.no
		};
		 let flag = app.check([
			{
				value: courierCodeValue,
				fn:(value) => {
					if(value == ''){
						app.errorToast(FormCheckRule.courierNullMessage);
						return false;
					}else {
						return true;
					}
				}
			}
		]);
		if (!flag) {
			return false;
		}
		this.setHistory(history);
		let formResult = {
			comName: express.com,
			comNo: express.no,
			inputValue: courierCodeValue
		};

		let opt = {
			url: app.globalData.host+"/wx/sd/queryEms.ajax",
			data: formResult,
			sucFn:(result) => {
				let infoList = result.body.infoList;
				if(infoList){					
					formResult['infoList'] = infoList
					app.setStorageSync(app.globalData.checkProgress, formResult);
					app.navigateTo({url:'../checkProgress/checkProgress'})						
				}else{
					app.errorToast('未查到该邮件的进度，请确认邮件号是否填写正确！');					
				}
				
			}
		};
		app.ajax(opt);
	},
});
